
/* jSlider, a slider Plugin for jQuery
 * Author: David Gonzalez
 * License: LGPL
 * Version: 1
 * Release: 2010-02-01
 */ 
;(function($){ 
		   
$.fn.slider = function( arg1 , arg2 ){
	
	function moveHandler(e){
		var d = e.data.data();
		var v = (d.max-d.min)*(e.clientX-e.data.offset().left-d.knobw/2)/(e.data.width()-d.knobw)+d.min;
		if(d.step != 0){
			var t = ((v)/d.step).toFixed(0)*d.step;
			if (t != d.val){
				d.val = t;
				draw(e.data);
			}
		}else{
			d.val = v;
			draw(e.data);
		}
	}
	
	function clicHandler(e){							
		$(document).bind("mouseup",e.data, function(f){
			$(document).unbind('mousemove');
			$(document).unbind('mouseup');
			f.data.data().onfinish(f.data.data("val"));
			return false;
		});
		$(document).bind("mousemove",e.data,moveHandler);
		moveHandler(e);
		return false;
	}
	
	function draw(el){
		var d = el.data();
		if(d.val>d.max) d.val=d.max;
		if(d.val<d.min) d.val=d.min;
		d.knob.css('left',(el.width()-d.knobw)*(d.val-d.min)/(d.max-d.min)+"px");
		d.onchange(d.val);
	}
	
	if(typeof arg1 === "string" ){
		var $this = $(this);
		if (arg1 == "val"){
			if(arg2 === undefined){
				return $this.data("val");
			}else{
				$this.data("val",arg2);
				draw($this);
			}
		}else if (arg1 == "enable"){
			if($this.data("enabled") == false) $this.bind("mousedown",$this, clicHandler );
			$this.data("enabled",true);
		}else if(arg1 == "disable"){
			if($this.data("enabled") == true) $this.unbind("mousedown");
			$this.data("enabled",false);
		}else if(arg1 == "redraw"){
			draw($this);
		}
	}else{
		var options = $.extend({min: 0, max: 1, val: .5, step: 0, onchange: function(v){}, onfinish:function(v){},enabled:true}, arg1 || {});
		this.each(function() {
			var $this = $(this);
			$this .data("min",options.min)
					.data("max",options.max)
					.data("val",options.val)
					.data("step",options.step)
					.data("onchange",options.onchange)
					.data("onfinish",options.onfinish)
					.data("knob",$this.find(".knob"))
					.data("knobw",$this.find(".knob").width())
					.data("enabled",options.enabled)
			draw($this);
			if(options.enabled) $this.bind("mousedown",$this, clicHandler );
			$(window).resize(function(){draw($this);});
		});
	}
	return this;
};
})( jQuery );
